all_rar_files = Dir.glob(File.join(Rails.root, "books", "*.rar"))
all_bok_files = []
all_store_tasks = []

namespace :tayseer do

  desc "Create an admin user"
  task :create_admin => :environment do
    if User.find_by_username('admin')
      puts "Already have a user with username: admin"
    else
      User.create!(:username=>'admin', :password=>'admin',
        :password_confirmation=>'admin', :email=>'admin@zilmenna.com')
      puts "Created a user admin/admin"
    end
  end
  
  all_rar_files.each do |rar_filename|
    extracted_filename = `unrar lb #{rar_filename}`.strip
    bok_filename = File.join(File.dirname(rar_filename), extracted_filename)
    all_bok_files << bok_filename
    
    # Create a task that stores this book in database
    book_no = File.basename(rar_filename).sub('.rar', '')
    task_name = "store_#{book_no}"
    all_store_tasks << task_name
    desc "Add #{File.basename(bok_filename)} to database"
    task task_name =>
        [bok_filename, :environment] do |t|
      book = Shamela::Book.new(t.prerequisites.first)
      book.save_to_db
    end
  end
  
  desc "Add all books to database"
  task "store_all" => all_store_tasks do
    # Do nothing, all is done in environments
  end
  
  desc "post process Riyadh ElSalehin"
  task :post_process_riyadh => :environment do
    # Find section no
    Section.all.each do |section|
      if (section.title =~ /(\d+)\s*[\-\.]\s*/ || 100) < 5
        section.section_no = $1.to_i
        section.title = $'
        section.save
      end
    end
    # Find document no
    Document.all.each do |document|
      if (document.body =~ /(\d+)\s*[\-\.]\s*/ || 100) < 5
        document.document_no = $1.to_i
        document.body = $'
      end
      # Split into Arabic/english parts
      english_start = document.body =~ /\s*\d*\s*[\-\.]?\s*[a-zA-Z]/
      if english_start
        document.description = document.body[english_start..-1]
        document.body = document.body[0, english_start]
        # remove number from english text
        if (document.description =~ /(\d+)\s*[\-\.]\s*/ || 100) < 5
          document.description = $'
        end
      end
      document.save
    end
  end
end

all_rar_files.each_with_index do |rar_filename, i|
  bok_filename = all_bok_files[i]
  desc "Extract file #{File.basename(rar_filename)}"
  task bok_filename => rar_filename do |t|
    `unrar e #{t.prerequisites.first} #{File.dirname(t.name)}`
  end
end
